package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruan.entity.R;
import com.ruan.entity.User;
import com.ruan.mapper.UserMapper;
import com.ruan.service.UserService;
import com.ruan.service.VerifyCodeService;
import com.ruan.utils.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName:VerifyCodeServiceImpl
 * @Author:阮昇
 * @Description:
 * @Datetime: 2023/9/7 14:26
 **/
@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    // 验证码前缀，这个是注册，的以后可能还会有订单
    static final String KEY_PREFIX = "user:code:phone:";
    static final Logger logger = LoggerFactory.getLogger(UserService.class);
    static final String regex = "[1][34578][0-9]{9}";//手机号码的格式：第一位只能为1，第二位可以是3，4，5，7，8，第三位到第十一位可以为0-9中任意一个数字
    @Override
    public R<Void> sendVerifyCode(String phoneNumber, String type) {
        if(!phoneNumber.matches(regex)){
            return new R<>(100,"电话号码格式不正确");
        }
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("phone_number", phoneNumber));
        if ("smsLogin".equals(type)){
            if (user == null){
                return new R<>(100,"该手机号未注册");
            }
        }
        if ("register".equals(type)){
            if (user != null){
                return new R<>(100,"该手机号已被注册");
            }
        }
        //生成6位验证码
        Random random = new Random();
        int code = random.nextInt(999999);
        if(code<100000){
            code = code + 100000;
        }

        try {
            HashMap<String, String> msg = new HashMap<>();
            msg.put("phone",phoneNumber);
            msg.put("code", String.valueOf(code));



            rabbitTemplate.convertAndSend("sms-exchange","sms-routing-key",msg);
            // 将code存入redis 5分钟失效
            redisCache.setCacheObject(KEY_PREFIX+phoneNumber,code,5, TimeUnit.MINUTES);
            return new R<>(200,"短信发送成功");
        } catch (AmqpException e) {
            logger.error("发送短信失败。phone:{}，code:{}",phoneNumber,code);
            return new R<>(100,"短信发送失败");
        }
    }
}
